package org.spider.spiderweb.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import org.spider.api.context.SpiderContext;
import org.spider.api.context.SpiderContextHolder;
import org.spider.api.domain.utilDomain.SpiderLog;
import org.spider.spiderweb.websocket.WebSocketContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

//WebSocketAppender 不保证线程安全的Appender类
public class WebSocketAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
    @Override
    protected void append(ILoggingEvent iLoggingEvent) {
        SpiderContext context = SpiderContextHolder.get();
        if (context instanceof WebSocketContext) {
            WebSocketContext socketContext = (WebSocketContext) context;
            Object[] argumentArray = iLoggingEvent.getArgumentArray();
            List<Object> arguments = argumentArray == null ? Collections.emptyList() :
                    new ArrayList<>(Arrays.asList(argumentArray));
            //异常 送到SpiderLog进行包装
            ThrowableProxy throwableProxy = (ThrowableProxy) iLoggingEvent.getThrowableProxy();
            if (throwableProxy != null) {
                arguments.add(throwableProxy.getThrowable());
            }
            socketContext.log(new SpiderLog(iLoggingEvent.getLevel().levelStr.toLowerCase(),
                    iLoggingEvent.getMessage(),
                    arguments));
        }
    }
}

